package com.leyou.filter;

import com.leyou.auth.pojo.Payload;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.cart.config.FilterProperties;
import com.leyou.cart.config.JwtProperties;
import com.leyou.utils.CookieUtils;
import com.leyou.utils.JsonUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 认证,鉴权过滤器
 *
 * @Author: Rose
 * @Date: 2021/4/11 11:21
 * @description ${description}
 * @version: 1.0.0
 */
@Slf4j
@Component
@EnableConfigurationProperties(value = {JwtProperties.class, FilterProperties.class})
public class AuthFilter extends ZuulFilter {


    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private FilterProperties filterProperties;

    /**
     * 属于哪种过滤器
     *
     * @return
     */
    @Override
    public String filterType() {
        // 过滤器的类型, 前置过滤器
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器的执行时机 ,把它放在 官方过滤器的前面
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;
    }

    /**
     * 是否进行过滤
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {

        // todo 判断请求路径 是否在白名单中

        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest request = ctx.getRequest();
        // 判断请求的url 路径
        String path = request.getRequestURI();
        // 判断是否放行, 放行,则返回 false
        return !isAllowPath(path);

    }

    /**
     * 判断此路径是否放行
     *
     * @param path
     * @return
     */
    private boolean isAllowPath(String path) {
        // 遍历白名单
        for (String allowPath : filterProperties.getAllowPaths()) {
            // 判断是否允许
            if (path.startsWith(allowPath)) {
                return true;
            }
        }
        return false;
    }


    /**
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest request = ctx.getRequest();
        // 获取cookie当中的token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        try {
            // 解析token
            Payload<UserInfo> fromToken = JwtUtils.getInfoFromToken(token, jwtProperties.getPubKey(), UserInfo.class);
            UserInfo userInfo = fromToken.getUserInfo();

            log.info("[zuul的认证,鉴权过滤器],拦截的token 信息为:{}", JsonUtils.tostring(userInfo));
            //  todo 校验权限


        } catch (Exception e) {
            // 解析token 失败, 未登录, 拦截
            ctx.setSendZuulResponse(false);
            // 返回状态码  403
            ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
        }
        return null;
    }
}
